import Cookies from "js-cookie";
import { useUserStoreHook } from "@/store/modules/user";
import { storageLocal, isString, isIncludeAllChildren } from "@pureadmin/utils";

import storm from "@/utils/storm";
import type { OAuth2, UserData } from "@/api/user";

const COOKIE_TOKEN = storm.env.toUpperCase() + "-STORM-TOKEN";
const TOKEN = "TOKEN";
const USER = "USER";
const ROLES = "ROLES";
const PERMISSIONS = "PERMISSIONS";

export interface DataInfo<T> {
  /** token */
  accessToken: string;
  /** `accessToken`的过期时间（时间戳） */
  expires: T;
  /** 用于调用刷新accessToken的接口时所需的token */
  refreshToken: string;
  /** 头像 */
  avatar?: string;
  /** 用户名 */
  username?: string;
  /** 昵称 */
  nickname?: string;
  /** 当前登录用户的角色 */
  roles?: Array<string>;
  /** 当前登录用户的按钮级别权限 */
  permissions?: Array<string>;
}

export const userKey = "user-info";
export const TokenKey = "authorized-token";
/**
 * 通过`multiple-tabs`是否在`cookie`中，判断用户是否已经登录系统，
 * 从而支持多标签页打开已经登录的系统后无需再登录。
 * 浏览器完全关闭后`multiple-tabs`将自动从`cookie`中销毁，
 * 再次打开浏览器需要重新登录系统
 * */
export const multipleTabsKey = "multiple-tabs";

/** 格式化token（jwt格式） */
export const formatToken = (token: string): string => {
  return "Bearer " + token;
};

/** 是否有按钮级别的权限（根据登录接口返回的`permissions`字段进行判断）*/
export const hasPerms = (value: string | Array<string>): boolean => {
  if (!value) return false;
  const allPerms = "*:*:*";
  const { permissions } = useUserStoreHook();
  if (!permissions) return false;
  if (permissions.length === 1 && permissions[0] === allPerms) return true;
  const isAuths = isString(value)
    ? permissions.includes(value)
    : isIncludeAllChildren(value, permissions);
  return isAuths ? true : false;
};

export function getToken(): string {
  const sessionToken = sessionStorage.getItem(TOKEN);
  if (sessionToken) {
    return sessionToken;
  }
  const cookieToken = Cookies.get(COOKIE_TOKEN);
  if (cookieToken) {
    sessionStorage.setItem(TOKEN, cookieToken);
    return cookieToken;
  }
  return null as unknown as string;
}

export function setToken(oAuth2: OAuth2) {
  // const token = oAuth2.access_token;
  const token = oAuth2.id_token;
  sessionStorage.setItem(TOKEN, token);
  Cookies.set(COOKIE_TOKEN, token, {
    domain: storm.env === "local" ? "localhost" : `.${storm.domain}`,
    expires: new Date(new Date().getTime() + oAuth2.expires_in * 1000)
  });
}

export function removeToken() {
  sessionStorage.removeItem(TOKEN);
  Cookies.remove(COOKIE_TOKEN, {
    domain: storm.env === "local" ? "localhost" : `.${storm.domain}`
  });
}

export const authorization = (token: string): string => {
  return "Bearer " + token;
};

export function getUser(): UserData {
  const value = sessionStorage.getItem(USER);
  if (value) {
    return JSON.parse(value);
  }
  return null as unknown as UserData;
}

export function setUser(user: UserData): void {
  const value = JSON.stringify(user);
  sessionStorage.setItem(USER, value);
}

export function removeUser(): void {
  sessionStorage.removeItem(USER);
}

export function getRoles(): string[] {
  const value = sessionStorage.getItem(ROLES);
  if (value) {
    return JSON.parse(value);
  }
  return null as unknown as string[];
}

export function setRoles(roles: string[]): void {
  sessionStorage.setItem(ROLES, JSON.stringify(roles));
}

export function removeRoles() {
  sessionStorage.removeItem(ROLES);
}

export function getPermissions(): string[] {
  const value = sessionStorage.getItem(PERMISSIONS);
  if (value) {
    return JSON.parse(value);
  }
  return null as unknown as string[];
}

export function setPermissions(permissions: string[]) {
  sessionStorage.setItem(PERMISSIONS, JSON.stringify(permissions));
}

export function removePermissions() {
  sessionStorage.removeItem(PERMISSIONS);
}
